<template>
	<view class="">
		<view class="login-box">
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-forms-item label="账号" name="id" class="login-input">
					<uni-easyinput class=" login-id" type="text" v-model="formData.id" placeholder="请输入账号" />
				</uni-forms-item>
				<uni-forms-item label="密码" name="password" class="login-input">
					<uni-easyinput class="login-password" type="password" v-model="formData.password"
						placeholder="请输入密码" />
				</uni-forms-item>
			</uni-forms>
			<p class="others">
				<span @click="toRegister">注册</span>
			</p>
			<button type="primary" class="login-btn" @click="submit">登录</button>
		</view>
	</view>
</template>

<script>
	import {
		callCloudFunction
	} from '@/api/requests.js'
	export default {
		data() {
			return {
				formData: {
					id: '',
					password: ''
				},
				rules: {
					id: {
						rules: [{
							required: true,
							errorMessage: '请输入账号',
						}, ]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请输入密码',
						}, ]
					}
				}
			}
		},
		methods: {
			submit() {
				this.$refs.form.validate().then(res => {
					const {
						id,
						password
					} = this.formData
					this.handleLogin(id, password)
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			toRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				});
			},
			handleLogin(id, password) {
				const data = {
					id: id,
					password: password
				}
				callCloudFunction('checkAccount', data, res => {
					if(res.result.data.length == 1 && res.result.data[0]){
						uni.setStorage({
							key: 'userInfo',
							data: res.result.data[0],
							success: function() {
								uni.switchTab({
									url: '/pages/statistic/statistic'
								});
							}
						});
					}else{
						uni.showModal({
							content: `查不到账号`,
							showCancel: false
						})
					}
					},
					err => {
						uni.showModal({
							content: `验证失败`,
							showCancel: false
						})
					})
			}
		},
		mounted() {
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				const {
					id,
					password
				} = userInfo
				this.handleLogin(id, password)
			}
		}
	}
</script>

<style>
	.login-input {
		margin: 10px;
	}

	.login-btn {
		width: 100px;
		height: 40px;
		margin: 0 auto;
		line-height: 40px;
	}

	.login-box p.others {
		width: 100px;
		margin: 50rpx auto;
		text-align: center;
	}
</style>